import { IpcMainEvent, IpcMainInvokeEvent, dialog, ipcMain } from 'electron'
import { IPCEvent } from '@common/constant'
import * as query from './query'
import config from './config'
import { initTable } from './tables'

ipcMain.handle(
  IPCEvent.SQL,
  (_event: IpcMainInvokeEvent, sql: string, type: SqlActionType, params = {}) => {
    return query[type](sql, params)
  }
)

ipcMain.handle(IPCEvent.SELECT_DATABASE, async () => {
  const res = await dialog.showOpenDialog({
    // 标题
    title: '选择目录',
    // 打开目录，创建目录
    properties: ['openDirectory', 'createDirectory']

    // // 文件类型限制
    // filters: [
    //   {
    //     name: 'Images',
    //     extensions: ['jpg', 'png', 'gif']
    //   }
    // ]
  })
  console.log(res.canceled, res.filePaths[0], 27)

  return res.canceled ? '' : res.filePaths[0]
})

ipcMain.on(IPCEvent.SET_DATABASE_DIRECTORY, (_event: IpcMainEvent, path: string) => {
  console.log(path, 34)

  config.databaseDirectory = path
})

ipcMain.on(IPCEvent.INIT_TABLE, () => {
  initTable()
})
